package day5.phenomenons;

/**
 * 加锁方式四：创建一个锁对象
 * 加锁成功
 */
public class Demo4 {

    // 定义一个被操作的数
    static int r = 0;
    // 定义操作的数
    static final int COUNT = 1000_0000;
    // 定义一个锁
    static Object lock = new Object();

    static class Add extends Thread {
        @Override
        public void run() {
            synchronized (lock) {
                for (int i = 0; i < COUNT; i++) {
                    r++;
                }
            }
        }
    }

    static class Sub extends Thread {
        @Override
        public void run() {
            synchronized (lock) {
                for (int i = 0; i < COUNT; i++) {
                    r--;
                }
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread add = new Add();
        add.start();
        Thread sub = new Sub();
        sub.start();

        // 等待结束
        add.join();
        sub.join();

        System.out.println(r);
    }
}
